import chalk from 'chalk';
import fs from 'fs-extra';
import { execa } from 'execa';
import readline from 'readline-sync'
import { fileURLToPath } from 'url';
import path from 'path'; 
import compressUUID from './uuidCompress.js';

const step = msg => console.log(chalk.cyan(msg));

const run = function (bin, args = [], opts = {}) {
  return execa(bin, args, { stdio: 'inherit', ...opts });
}
const commonCtx = JSON.parse(fs.readFileSync('dev/commonFiles.json', 'utf-8'));

const __dirname =  path.dirname(fileURLToPath(import.meta.url));

const commons = Object.keys(commonCtx.common);

const libsInfo = commonCtx.libsInfo;

const packageCt = JSON.parse(fs.readFileSync('package.json', 'utf-8'));

const fetchLibs = [];

const commonLibsUrl = 'https://e.coding.net/thinkingltv/tk_pa/tk_common_playable.git';

async function deleteFolder() {
  try {
    step('开始删除本地文件');
    await run('rm', ['-rf', 'tempDir']);
    console.log(chalk.green('删除本地文件完成'));
  } catch (error) {
    console.log(chalk.red('删除本地文件失败'));
  }
}

async function localResolve() {
  try {
    for (const lib of fetchLibs) {
      for (let i = 0; i < libsInfo.length; i++) {
        if (libsInfo[i].name == lib) {
          await fs.copySync('./tempDir' + libsInfo[i]["remotePath"], libsInfo[i]["localPath"]);
          break;
        }
      }
    }
    
    console.log(chalk.green('同步到本地完成'));
    console.log(chalk.green('同步了' + fetchLibs.toString() + '公共库'));
  } catch (error) {
    console.log(chalk.red('同步到本地失败'));
    console.log(chalk.red(error));
  }
}

async function syncUUID(currentProject = '') {
  try {
    step('开始同步uuid');
    const metaList = listFile('./assets/scripts', '.ts.meta');
    const newUUIDInfo = {}, oldUUIDInfo = {};
    const uuidDB = JSON.parse(fs.readFileSync('./dev/uuid.json', 'utf-8'));
    metaList.forEach(item => {
      const content = JSON.parse(fs.readFileSync(item, 'utf-8'));
      const key = item.replace('.ts.meta', '').split('/').pop();
      if(uuidDB[key]) {
        newUUIDInfo[key] = compressUUID(content.uuid);
        oldUUIDInfo[key] = compressUUID(uuidDB[key][currentProject]);
      }
    });
    // 遍历一次assets,找出.scene里需要替换的uuid
    const sceneList = listFile('./assets/scenes', '.scene', 2);
    console.log(oldUUIDInfo, newUUIDInfo);
    sceneList.forEach(scene => {
      let content = fs.readFileSync(scene, 'utf-8');
      for(const uuidKey in oldUUIDInfo){
        content = content.replace(new RegExp(oldUUIDInfo[uuidKey], "g"), newUUIDInfo[uuidKey]);
        fs.writeFileSync(scene, content);
      }
    })
  }
  catch (error){
    console.log(chalk.red('同步uuid失败'));
    console.log(chalk.red(error));
  }
}

function listFile(dir, flag = '', depth, currentDepth = 0, list = []) {
  if(currentDepth > depth) return;
  let files = fs.readdirSync(dir);
  files.forEach(file => {
    let filePath = path.join(dir, file);
    let stats = fs.statSync(filePath);
    if (stats.isDirectory()) {
      listFile(filePath, flag, depth, currentDepth + 1, list);
    }else if(filePath.endsWith(flag)) {
      list.push(filePath);
    }
  })
  return list;
}

async function libsSelect() {
  try {
    await deleteFolder();
    await run('mkdir', ['tempDir']);
    await run('git', ['init'], { cwd: 'tempDir' });
    await run('git', ['remote', 'add', '-f', 'origin', commonLibsUrl], { cwd: 'tempDir' });
    await step('从仓库中检索到如下公共库:')
    commons.forEach((val, index) => console.log(chalk.green(`${index + 1}. ${val}` + '\n')));
    let res = readline.question("请输入需要同步的公共库序号(如果包含多个库用','分隔)：)");
    res = res.split(',');
    await step('开启sparse checkout模式');
    await run('git', ['config', 'core.sparsecheckout', 'true'], { cwd: 'tempDir' });
    for (const r of res) {
      const parsedIndex = parseInt(r) - 1;
      if (!isNaN(parsedIndex) && parsedIndex >= 0 && parsedIndex < commons.length) {
        fetchLibs.push(commons[parsedIndex]);
        const selectedCommon = commonCtx.common[commons[parsedIndex]];
        await fs.appendFile('./tempDir/.git/info/sparse-checkout', selectedCommon + '\n');
      } else {
        console.log(chalk.yellow(`忽略无效的输入：${r}`));
      }
    }
    await run('git', ['pull', 'origin', 'master', '--depth=1'], { cwd: 'tempDir' });
  } catch (error) {
    console.log(error);
    console.log(chalk.red('同步到本地失败'));
  }
}

async function markFile() {
  try {
    let keys = Object.keys(packageCt);
    if (keys.includes("file")) {
      let k = Object.keys(packageCt.file);
      for (let item of fetchLibs) {
        if (!k.includes(item)) {
          packageCt.file[item] = '0.0.1';
        }
      }
      fs.writeFileSync('package.json', JSON.stringify(packageCt, packageCt, 2));
    } else {
      packageCt['file'] = {};
      for (let item of fetchLibs) {
        packageCt['file'][item] = '0.0.1';
        fs.writeJSONSync('package.json', packageCt);
      }
    }
    console.log(chalk.green('数据写入成功'));
  } catch (err) {
    console.log(err);
    console.log(chalk.red('数据写入失败'));
  }
}

async function main() {
  await libsSelect();
  await localResolve();
  await markFile();
  await deleteFolder();
  // await syncUUID(packageCt.name.split('_')[1]);

}

main();
